import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liuzhaoqiang
 */
public class LeetCode49 {
    public static void main(String[] args) {
        LeetCode49 leetCode49 = new LeetCode49();
        List<List<String>> lists = leetCode49.groupAnagrams(new String[]{"eat", "tea", "tan", "ate", "nat", "bat"});
        System.out.println(lists);
    }

    public List<List<String>> groupAnagrams(String[] strs) {
        Map<String,List<String>> map = new HashMap<>();
        for (String str : strs) {
            String key = sortStr(str);
            if(map.containsKey(key)){
                List<String> list = map.get(key);
                list.add(str);
            }else{
                map.put(key,new ArrayList<>());
                map.get(key).add(str);
            }
        }
        return map.values().stream().collect(Collectors.toList());
    }

    public static String sortStr(String str){
        char[] chars = str.toCharArray();
        Arrays.sort(chars);
        return new String(chars);
    }
}
